package com.pig4cloud.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.mall.product.dto.QueryReq;
import com.pig4cloud.mall.product.entity.*;
import com.pig4cloud.mall.product.enums.AttrEnum;
import com.pig4cloud.mall.product.mapper.*;
import com.pig4cloud.mall.product.service.AttrService;
import com.pig4cloud.mall.product.vo.AttrResVo;
import com.pig4cloud.mall.product.vo.BaseAttr;
import com.pig4cloud.mall.product.vo.GroupVo;
import com.pig4cloud.mall.product.vo.SaleAttr;
import com.pig4cloud.pig.common.core.util.PageResult;
import com.pig4cloud.pig.common.core.util.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品属性
 *
 * @author fangyu
 * @date 2020-11-25 15:05:14
 */
@Service
public class AttrServiceImpl extends ServiceImpl<AttrMapper, Attr> implements AttrService {

	@Autowired
	private AttrMapper attrMapper;
	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private AttrGroupMapper attrGroupMapper;
	@Autowired
	private ProductAttrValueMapper productAttrValueMapper;
	@Autowired
	private AttrAttrGroupRelationMapper attrAttrGroupRelationMapper;

	@Override
	public PageResult queryPage(Map<String, Object> params, Long spuId) {
		IPage<ProductAttrValue> page;
		if (spuId == 0) {
			page = productAttrValueMapper.selectPage(new QueryReq<ProductAttrValue>().getPage(params), new QueryWrapper<ProductAttrValue>());
		} else {
			// select * from pms_attr_group where
			QueryWrapper<ProductAttrValue> wrapper = new QueryWrapper<ProductAttrValue>().eq("spu_id", spuId);
			page = productAttrValueMapper.selectPage(new QueryReq<ProductAttrValue>().getPage(params), wrapper);
		}
		return new PageResult(page);
	}

	@Override
	public PageResult queryPageByCid(Map<String, Object> params, String attrType, Long catId) {
		QueryWrapper<Attr> wrapper = new QueryWrapper<>();
		String key = (String) params.get("key");
		if (StringUtils.isNotEmpty(key)) {
			// 如果key不为空，则加上 `where attr_id = '%key%' or attr_name = '%key%'` 的查询条件
			wrapper.and((obj) -> {
				obj.eq("attr_id", key).or().eq("attr_name", key);
			});
		}
		IPage<Attr> page;
		if (catId != 0) {
			// 如果catId 不为0, 则加上 catelog_id = catId 的查询条件
			wrapper.eq("catelog_id", catId);
		}
		wrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? AttrEnum.ATTR_TYPE_BASE.getCode() : AttrEnum.ATTR_TYPE_SALE.getCode());
		page = this.page(new QueryReq<Attr>().getPage(params), wrapper);
		PageResult pageResult = PageResult.buildPage(page);
		List<Attr> records = page.getRecords();
		// 需要将groupName 和 categoryName 一同返回
		List<AttrResVo> attrResVoList = records.stream().map((attr -> {
			AttrResVo attrResVo = new AttrResVo();
			BeanUtils.copyProperties(attr, attrResVo);
			AttrAttrGroupRelation attrAttrGroupRelation = attrAttrGroupRelationMapper.selectOne(new QueryWrapper<AttrAttrGroupRelation>().eq("attr_id", attr.getAttrId()));
			if ("base".equalsIgnoreCase(attrType)) {
				if (attrAttrGroupRelation != null && attrAttrGroupRelation.getAttrGroupId() != null) {
					AttrGroup attrGroup = attrGroupMapper.selectById(attrAttrGroupRelation.getAttrGroupId());
					attrResVo.setAttrGroupId(attrGroup.getAttrGroupId());
					attrResVo.setGroupName(attrGroup.getAttrGroupName());
				}
			}
			Category category = categoryMapper.selectById(attr.getCatelogId());
			if (category != null) {
				attrResVo.setCategoryName(category.getName());
			}
			return attrResVo;
		})).collect(Collectors.toList());
		pageResult.setList(attrResVoList);
		return pageResult;
	}

	@Override
	public R queryBaseAttrByCid(Long catId) {
		List<BaseAttr> list = attrMapper.queryBaseAttrByCid(catId);
		List<BaseAttr> baseAttrList = new ArrayList<>();
		// 查询结果判断类型并加入 按钮类型
		list.forEach(attr -> {
			BaseAttr baseAttr = new BaseAttr();
			BeanUtils.copyProperties(attr, baseAttr);
			if (attr.getValueType() == 0) {
				baseAttr.setType("radio");
			} else if (attr.getValueType() == 1) {
				baseAttr.setType("multiple");
			}
			baseAttr.setDicData(attr.getValueSelect());
			baseAttrList.add(baseAttr);
		});
		List<GroupVo> groupVoList = new ArrayList<>();
		// 排序 分组 并转换为 GroupVo List
		baseAttrList.stream()
				.sorted(Comparator.comparing(BaseAttr::getSort))
				.collect(Collectors.groupingBy(BaseAttr::getGroupName))
				.forEach((groupName, v) -> {
					GroupVo groupVo = new GroupVo();
					groupVo.setLabel(groupName);
					groupVo.setProp(groupName + System.currentTimeMillis());
					groupVo.setColumn(v);
					groupVoList.add(groupVo);
				});

		return R.ok(groupVoList);
	}

	@Override
	public R querySaleAttrByCid(Long catId) {
		List<SaleAttr> list = attrMapper.querySaleAttrByCid(catId);
		list.forEach(attr -> {
			attr.setDicData(attr.getValueSelect());
		});
		return R.ok(list);
	}
}
